package cn.zkw.util;

import net.sf.json.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;

/**
 *  根据IP地址获取详细的地域信息
 */
public class SendGetRequest {
    public static JSONObject getHttpResponseJson(String url, Map<String,String> param){
        CloseableHttpClient httpclient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        JSONObject jsonObject = null;
        try {
            Set<String> keySet= param.keySet();
            Iterator<String> iterator = keySet.iterator();
            StringBuffer stringBuffer = new StringBuffer("?");
            while(iterator.hasNext()){
                String key = iterator.next();
                stringBuffer.append(key+"=");
                stringBuffer.append(param.get(key)+"&");
            }
            url = url+stringBuffer.toString();
            //用get方法发送http请求
            HttpGet get = new HttpGet(url);
            System.out.println("执行get请求:...." + get.getURI());
            CloseableHttpResponse httpResponse = null;
            //发送get请求
            httpResponse = httpclient.execute(get);
            try {
                //response实体
                HttpEntity entity = httpResponse.getEntity();
                if (null != entity) {
                    System.out.println("响应状态码:" + httpResponse.getStatusLine());
                    System.out.println("-------------------------------------------------");
                    //EntityUtils.toString(entity)   不能多次读取，读取一次就会关闭输出流了
//                    System.out.println("响应内容:" + EntityUtils.toString(entity));
                    System.out.println("-------------------------------------------------");
                    jsonObject = JSONObject.fromObject(EntityUtils.toString(entity));
                }
            } finally {
                httpResponse.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return jsonObject;
    }
}
